package com.wkm.chainchain.deprecated_buildmock;

import com.wkm.chainchain.pbft.p2p.PBFTServer;
import com.wkm.chainchain.consensusutils.YamlUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.CountDownLatch;


/**
 * PBFT主函数 通过输入确定共识节点还是消息发送端口 注意java虚拟机内存的设置 线程开太多容易爆栈 -Xms1024m -Xmx1024m
 */
@Slf4j
public class PBFTBuild {
    // 服务端起始端口
    private static final int INITIAL_PORT;
    // 服务端节点数量
    private static final int NODE_AMOUNT;
    // 客户端端口
    private static final int CLIENT_PORT;


    static {
        // 读取配置
        YamlUtil yamlUtil = new YamlUtil();
        Map<String, Integer> map = yamlUtil.getYaml("const.yaml");
        INITIAL_PORT = map.get("INITIAL_PORT");
        NODE_AMOUNT = map.get("NODE_AMOUNT");
        CLIENT_PORT = map.get("CLIENT_PORT");
    }

    public static void main(String[] args) {
        Build();
    }

    public static void Build() {
        PBFTServer.getInstance(CLIENT_PORT);
        // 用来等待所有服务端节点都已经启动起来
        CountDownLatch serverNodeLatch = new CountDownLatch(NODE_AMOUNT);
        // 用来等待所有服务端节点之间都已经互相连接
        CountDownLatch nodeConnectedLatch = new CountDownLatch(NODE_AMOUNT);
        // 创建消息发送客户端
        Thread msgClient = new Thread(new MsgClient(serverNodeLatch, nodeConnectedLatch, CLIENT_PORT, INITIAL_PORT));
        msgClient.start();
        Thread[] threads = new Thread[NODE_AMOUNT];
        // 创建拜占庭共识算法节点
        for (int i = 0; i < NODE_AMOUNT; i++) {
            threads[i] = new Thread(new MsgServer(serverNodeLatch, nodeConnectedLatch, NODE_AMOUNT, INITIAL_PORT + i, i));
            threads[i].start();
        }
    }
}


